using Eno.Domain.Entity.App;
using Eno.Domain.Repositories;
using Eno.Infrastructure.DataBase;
using Eno.Infrastructure.InfRepositories;
using Eno.Infrastructure.Services;
using Eno.Infrastructure.Middleware;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Eno.Infrastructure;

public static class ServiceExtension
{
    public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
    {
        var _connStr = configuration.GetConnectionString("pgsql");
        if (string.IsNullOrWhiteSpace(_connStr))
            throw new ArgumentException("The connection string 'pgsql' is missing or empty.", nameof(_connStr));
        //! 将连接自符串注入定义的接口当中
        services.AddScoped<IUserRepository<AppUser>>(provider => new UserRepository(_connStr));
        services.AddScoped<IRepository<AppRole>>(provider => new RoleRepository(_connStr));
        services.AddScoped<IPermissionRepository<AppPermission>>(providr => new PermissionRepository(_connStr));
        services.AddScoped<IUserToRoleRepository>(provider => new CombineUserRoleToDelteteRepository(_connStr));
        services.AddScoped<IAppointOrReomoveRoleRepository>(provider => new AppointOrRemoveRoleRepository(_connStr));
        services.AddScoped<IRoleToPermissionRepository>(provider => new CombineRolePermissionRepository(_connStr));
        services.AddScoped<IDepartmentRepository<AppDepartment>>(provider => new DepartmentRepository(_connStr));
        services.AddScoped<IJwtService, JwtService>();
        
        //! 添加数据库库上下文
        services.AddDbContext<OriginDbContext>(t =>
        {
            t.UseNpgsql(_connStr);
            // 添加LoggingInterceptor到DbContext
            t.AddInterceptors(new LoggingInterceptor(services.BuildServiceProvider()));
        });
        
        return services;
    }
}